from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras import utils
import numpy as np

# Predicting animal type based on various features
#加载数据，并分割X,y
xy = np.loadtxt('data-04-zoo.csv', delimiter=',', dtype=np.float32)
x_data = xy[:, 0:-1]
y_data = xy[:, [-1]]
print(x_data.shape, y_data.shape)

#类别数=7
nb_classes = 7
# y_one_hot = utils.to_categorical(y_data, nb_classes)  #独热编码
# print(y_one_hot.shape)
#建立模型序列
model = Sequential()
model.add(Dense(nb_classes, input_shape=(16,)))
model.add(Activation('softmax'))

#模型结果输出
model.summary()

##使用sparse_categorical_crossentropy时,y不用独热;
# 使用categorical_crossentropy时,y需要使用独热-->utils.to_categorical(y_data, nb_classes)
model.compile(loss='sparse_categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

# history = model.fit(x_data, y_one_hot, epochs=1000)
#训练模型
history = model.fit(x_data, y_data, epochs=1000)

# Let's see if we can predict
#注意predict和predict_classes的区别
pred = model.predict(x_data)   #输出多分类预测值[0.1, 0.3, 0,4...]
pred_cls = model.predict_classes(x_data)  # 输出的是预测argmax结果
for p, y in zip(pred_cls, y_data):
    print("prediction: ", p, " true Y: ", y)
